package fragment;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import activity.MainOneActivity;
import activity.login.ActivityLogin;
import activity.luntan.ToPicDetailActivity;
import activity.store.GoodDetailActivity;
import adapter.ImagePagerAdapter;
import adapter.ShouYeAdapter;
import base.BaseFragment;
import base.MyApplcation;
import bean.LunBoBean;
import bean.ShouYeBean;
import presenter.LunBoPresenter;
import util.GlideLoader;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.SPUtils;
import util.volley.ResultEntity;
import widget.LoweLinearLayout;
import widget.MyGridView;
import widget.ThreeDPageTransformer;


/**
 * 首页
 */
public class IndexFragment extends BaseFragment implements Observer {
    LoweLinearLayout index_linea_roadsave, index_linea_qipeistore, index_linea_olddriver;
    ImageView close_icon;
    TextView add_shap_title_tv;
    LunBoPresenter lunBoPresenter;
    //    PtrFrameLayout commend_anchor_ptr;
    TextView add_lift_tv;
    //  BezierViewPager lunbo;//轮播图第二套效果，
    ViewPager lunbo;
    private ImagePagerAdapter adapter;
    private ArrayList<LunBoBean> lunboArray;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    private static final int BAIDU_READ_PHONE_STATE = 100;

    String versionNow;//版本号

    public static Double lat;
    public static Double lng;

    MyGridView mygridView;
    ShouYeAdapter shouYeAdapter;
    ShouYeBean bean;
    private List<ShouYeBean.Products> beanList;
    private List<ShouYeBean.Post> postList;
    ViewFlipper f_home;

    @Override
    public int initView() {
        return R.layout.fragment_index;
    }

    @Override
    public void onMyActivityCreated() {
        add_shap_title_tv.setText(getString(R.string.app_name));
        bean = new ShouYeBean();
        beanList = new ArrayList<>();
        postList=new ArrayList<>();
        add_lift_tv.setVisibility(View.VISIBLE);
        // close_icon.setImageResource(R.drawable.dingwei);
        add_lift_tv.setText("定位中");
        lunBoPresenter = new LunBoPresenter(this);
        lunBoPresenter.lunBoInfo("6079");
        lunBoPresenter.shouye("", "");
        mLocationClient = new LocationClient(getActivity().getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数

        isCameraPermission(getActivity(), 1);
        initLocation();

        //退出登录的广播
        IntentFilter intentFilterExit = new IntentFilter(
                "city");
        getActivity().registerReceiver(nichengBroadcastReceiver, intentFilterExit);

        //获取焦点。，去掉后每次页面返回，MyGridView会在上面
        lunbo.setFocusable(true);
        lunbo.setFocusableInTouchMode(true);
        lunbo.requestFocus();

        mygridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), GoodDetailActivity.class);
                intent.putExtra("goodsId", beanList.get(position).getId());
                intent.putExtra("goodsName", beanList.get(position).getName());
                if (beanList.get(position).getPrice().equals("")) {
                    intent.putExtra("money", "");
                } else {
                    intent.putExtra("money", Double.parseDouble(beanList.get(position).getPrice()) / 100 + "");
                }
                intent.putExtra("tehui", "1");
                startActivity(intent);
            }
        });

    }

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public static boolean isCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            int aPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
            int bPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            int cPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
            int dPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int ePermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (aPermission != PackageManager.PERMISSION_GRANTED || bPermission != PackageManager.PERMISSION_GRANTED || cPermission != PackageManager.PERMISSION_GRANTED || dPermission != PackageManager.PERMISSION_GRANTED || ePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS, requestCode);
                return false;
            }
        }
        return true;
    }

    private String city;
    private String qu;
    BroadcastReceiver nichengBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            city = (String) SPUtils.get(MyApplcation.ctx, null, Const.CITY, "");
            qu = (String) SPUtils.get(MyApplcation.ctx, null, Const.QU, "");
            Log.d("citiciif", city);
            add_lift_tv.setText(qu + "");
        }

        ;
    };

    public void onStop() {
        // TODO Auto-generated method stub
        mLocationClient.stop();
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(nichengBroadcastReceiver);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.add_lift_tv:
//                intent = new Intent(getActivity(), CityListActivity.class);
//                startActivityForResult(intent, 101);
                break;
            case R.id.index_linea_roadsave:
                if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
                    Intent intent1 = new Intent(getActivity(), ActivityLogin.class);
                    getActivity().startActivity(intent1);
                } else {
//                    intent = new Intent(getActivity(), DriverRepair.class);
//                    intent.putExtra("city", city + "");
//                    startActivity(intent);
                    MainOneActivity.onSetFragment().setTabSelection(2);
                }
                break;

            case R.id.index_linea_qipeistore:
                MainOneActivity.onSetFragment().setTabSelection(1);
                break;
            case R.id.index_linea_olddriver:
                MainOneActivity.onSetFragment().setTabSelection(3);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 102) {
            city = data.getStringExtra("choose");
            add_lift_tv.setText(city + "");

        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == LunBoPresenter.lunbo_success) {
                lunboArray = (ArrayList<LunBoBean>) entity.getData();
                //setLunBoData();//使用第二套轮播效果，把下面的代码隐藏   start();//图片开始轮播
                adapter = new ImagePagerAdapter(getActivity(), lunboArray);
                lunbo.setAdapter(adapter);
                // 缓存的页面数
                lunbo.setOffscreenPageLimit(3);
                //间距
                lunbo.setPageMargin(8);
                start();//图片开始轮播
                lunbo.post(new Runnable() {
                    @Override
                    public void run() {
                        int paddingLeft = lunbo.getPaddingLeft();

                        int imgWidth = lunbo.getWidth() - paddingLeft * 2;
                        float excursion = -(float) paddingLeft / (float) imgWidth;
                        lunbo.setPageTransformer(true, new ThreeDPageTransformer(excursion));
                        adapter.notifyDataSetChanged();
                    }
                });
                lunbo.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                    @Override
                    public void onPageSelected(int arg0) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onPageScrolled(int arg0, float arg1, int arg2) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onPageScrollStateChanged(int arg0) {
                        // TODO Auto-generated method stub
                        switch (arg0) {
                            case ViewPager.SCROLL_STATE_DRAGGING:
                                handler.removeMessages(1);
                                break;
                            case ViewPager.SCROLL_STATE_IDLE:
                                handler.sendEmptyMessageDelayed(1, durating);
                                break;
                            default:
                                break;
                        }
                    }
                });
            } else if (entity.getEventType() == LunBoPresenter.lunbo_fail) {
                ByAlert.alert("" + entity.getMsg());
            } else
                //首页数据
            if (entity.getEventType() == LunBoPresenter.shouye_success) {
                bean = (ShouYeBean) entity.getData();
                beanList.addAll(bean.getProducts());

                shouYeAdapter = new ShouYeAdapter(getActivity(), beanList);
                mygridView.setAdapter(shouYeAdapter);

                postList.addAll(bean.getPost());
                for (int i = 0; i < postList.size(); i++) {
                    View layout= LinearLayout.inflate(getActivity(),R.layout.item_home_notify, null);
                    TextView xiaoxi_title,xiaoxi_zhuti,xiaoxi_content;
                    ImageView xiaoxi_img,xiaoxi_imgs;
                    xiaoxi_img= (ImageView) layout.findViewById(R.id.xiaoxi_img);
                    xiaoxi_imgs= (ImageView) layout.findViewById(R.id.xiaoxi_imgs);
                    xiaoxi_title= (TextView) layout.findViewById(R.id.xiaoxi_title);
                    xiaoxi_zhuti= (TextView) layout.findViewById(R.id.xiaoxi_zhuti);
                    xiaoxi_content= (TextView) layout.findViewById(R.id.xiaoxi_content);
                    GlideLoader.displayImageHeadCircular(postList.get(i).getUid()+"",xiaoxi_img);
                    if (postList.get(i).getImg().equals("0")){
                        xiaoxi_imgs.setVisibility(View.GONE);
                    }else{
                        xiaoxi_imgs.setVisibility(View.VISIBLE);
                        GlideLoader.displayImages(postList.get(i).getImg()+"",xiaoxi_imgs);
                    }
                    xiaoxi_title.setText(postList.get(i).getUname());
                    xiaoxi_zhuti.setText(postList.get(i).getTitle());
                    xiaoxi_content.setText(postList.get(i).getContent());
                    f_home.addView(layout);
                }
                f_home.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id=postList.get(f_home.getDisplayedChild()).getId();
                        Intent intent = new Intent(getActivity(), ToPicDetailActivity.class);
                        intent.putExtra("id",id);
                        startActivity(intent);
                    }
                });
            } else if (entity.getEventType() == LunBoPresenter.shouye_fail) {
                ByAlert.alert("111" + entity.getMsg());
            }

        }
    }

//    private void setLunBoData() {
//        int mWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
//        float heightRatio = 0.565f;  //高是宽的 0.565 ,根据图片比例
//
//        CardPagerAdapter cardAdapter = new CardPagerAdapter(getActivity());
//        cardAdapter.addImgUrlList(lunboArray);
//
//
//        //设置阴影大小，即vPage  左右两个图片相距边框  maxFactor + 0.3*CornerRadius   *2
//        //设置阴影大小，即vPage 上下图片相距边框  maxFactor*1.5f + 0.3*CornerRadius
//        int maxFactor = mWidth / 25;
//        cardAdapter.setMaxElevationFactor(maxFactor);
//
//        int mWidthPading = mWidth / 8;
//
//        //因为我们adapter里的cardView CornerRadius已经写死为10dp，所以0.3*CornerRadius=3
//        //设置Elevation之后，控件宽度要减去 (maxFactor + dp2px(3)) * heightRatio
//        //heightMore 设置Elevation之后，控件高度 比  控件宽度* heightRatio  多出的部分
//        float heightMore = (1.5f * maxFactor + dp2px(3)) - (maxFactor + dp2px(3)) * heightRatio;
//        int mHeightPading = (int) (mWidthPading * heightRatio - heightMore);
//
//        lunbo.setLayoutParams(new LinearLayout.LayoutParams(mWidth, (int) (mWidth * heightRatio)));
//        lunbo.setPadding(mWidthPading, mHeightPading, mWidthPading, mHeightPading);
//        lunbo.setClipToPadding(false);
//        lunbo.setAdapter(cardAdapter);
//        lunbo.showTransformer(0.2f);
//        cardAdapter.setOnCardItemClickListener(new CardPagerAdapter.OnCardItemClickListener() {
//            @Override
//            public void onClick(int position) {
//                if(!lunboArray.get(position).getUrl().equals("")){
//                    Intent intent = new Intent(getActivity(), YinLianWebActivity.class);
//                    intent.putExtra("url", lunboArray.get(position).getUrl());
//                    intent.putExtra("title", lunboArray.get(position).getTitle().equals("")?"虎头奔":lunboArray.get(position).getTitle());
//                    startActivity(intent);
//                }
//            }
//        });
//    }

    private long durating = 2000;// 切换间隔
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                lunbo.setCurrentItem((lunbo.getCurrentItem() + 1) % lunboArray.size());
                //start();
            } catch (Exception e) {

            }
        }

        ;
    };

    public void start() {
        handler.sendEmptyMessageDelayed(1, durating);
    }

    public void start(View view) {
        mLocationClient.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                } else {
                    // 没有获取到权限，做特殊处理
                }
                break;
            default:
                break;
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            if (location != null) {
                lat = location.getLatitude();
                lng = location.getLongitude();
            }

            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());
            //   ByAlert.alert(sb.toString());
            add_lift_tv.setText(location.getDistrict());
            SPUtils.put(getActivity(), null,
                    Const.QU, location.getDistrict());
        }
    }

}
